<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>OpenCV: Hough Circle Transform</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"/></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div id="nav-path" class="navpath">
  <ul>
<li class="navelem"><a class="el" href="../../d9/df8/tutorial_root.html">OpenCV Tutorials</a></li><li class="navelem"><a class="el" href="../../d7/da8/tutorial_table_of_content_imgproc.html">Image Processing (imgproc module)</a></li>  </ul>
</div>
</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">Hough Circle Transform </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><b>Prev Tutorial:</b> <a class="el" href="../../d9/db0/tutorial_hough_lines.html">Hough Line Transform</a></p>
<p><b>Next Tutorial:</b> <a class="el" href="../../d1/da0/tutorial_remap.html">Remapping</a></p>
<table class="doxtable">
<tr>
<th align="right"></th><th align="left"></th></tr>
<tr>
<td align="right">Original author </td><td align="left">Ana Huamán </td></tr>
<tr>
<td align="right">Compatibility </td><td align="left">OpenCV &gt;= 3.0 </td></tr>
</table>
<h2>Goal </h2>
<p>In this tutorial you will learn how to:</p>
<ul>
<li>Use the OpenCV function <b><a class="el" href="../../dd/d1a/group__imgproc__feature.html#ga47849c3be0d0406ad3ca45db65a25d2d" title="Finds circles in a grayscale image using the Hough transform. ">HoughCircles()</a></b> to detect circles in an image.</li>
</ul>
<h2>Theory </h2>
<h3>Hough Circle Transform</h3>
<ul>
<li>The Hough Circle Transform works in a <em>roughly</em> analogous way to the Hough Line Transform explained in the previous tutorial.</li>
<li><p class="startli">In the line detection case, a line was defined by two parameters \((r, \theta)\). In the circle case, we need three parameters to define a circle:</p>
<p class="formulaDsp">
\[C : ( x_{center}, y_{center}, r )\]
</p>
<p class="startli">where \((x_{center}, y_{center})\) define the center position (green point) and \(r\) is the radius, which allows us to completely define a circle, as it can be seen below:</p>
<div class="image">
<img src="../../Hough_Circle_Tutorial_Theory_0.jpg" alt="Hough_Circle_Tutorial_Theory_0.jpg"/>
</div>
</li>
<li>For sake of efficiency, OpenCV implements a detection method slightly trickier than the standard Hough Transform: <em>The Hough gradient method</em>, which is made up of two main stages. The first stage involves edge detection and finding the possible circle centers and the second stage finds the best radius for each candidate center. For more details, please check the book <em>Learning OpenCV</em> or your favorite Computer Vision bibliography</li>
</ul>
<h4>What does this program do?</h4>
<ul>
<li>Loads an image and blur it to reduce the noise</li>
<li>Applies the <em>Hough Circle Transform</em> to the blurred image .</li>
<li>Display the detected circle in a window.</li>
</ul>
<h2>Code </h2>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'><p> The sample code that we will explain can be downloaded from <a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/cpp/tutorial_code/ImgTrans/houghcircles.cpp">here</a>. A slightly fancier version (which shows trackbars for changing the threshold values) can be found <a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/cpp/tutorial_code/ImgTrans/HoughCircle_Demo.cpp">here</a>. </p><div class="fragment"><div class="line"></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d6/d87/imgcodecs_8hpp.html">opencv2/imgcodecs.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d4/dd5/highgui_8hpp.html">opencv2/highgui.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d1/d4f/imgproc_2include_2opencv2_2imgproc_8hpp.html">opencv2/imgproc.hpp</a>&quot;</span></div><div class="line"></div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d2/d75/namespacecv.html">cv</a>;</div><div class="line"><span class="keyword">using namespace </span>std;</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main(<span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>** argv)</div><div class="line">{</div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span>* filename = argc &gt;=2 ? argv[1] : <span class="stringliteral">&quot;smarties.png&quot;</span>;</div><div class="line"></div><div class="line">    <span class="comment">// Loads an image</span></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>( filename ), <a class="code" href="../../d8/d6a/group__imgcodecs__flags.html#gga61d9b0126a3e57d9277ac48327799c80af660544735200cbe942eea09232eb822">IMREAD_COLOR</a> );</div><div class="line"></div><div class="line">    <span class="comment">// Check if image is loaded fine</span></div><div class="line">    <span class="keywordflow">if</span>(src.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#abbec3525a852e77998aba034813fded4">empty</a>()){</div><div class="line">        printf(<span class="stringliteral">&quot; Error opening image\n&quot;</span>);</div><div class="line">        printf(<span class="stringliteral">&quot; Program Arguments: [image_name -- default %s] \n&quot;</span>, filename);</div><div class="line">        <span class="keywordflow">return</span> EXIT_FAILURE;</div><div class="line">    }</div><div class="line"></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> gray;</div><div class="line">    <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cvtColor</a>(src, gray, <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#gga4e0972be5de079fed4e3a10e24ef5ef0a353a4b8db9040165db4dacb5bcefb6ea">COLOR_BGR2GRAY</a>);</div><div class="line"></div><div class="line">    <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga564869aa33e58769b4469101aac458f9">medianBlur</a>(gray, gray, 5);</div><div class="line"></div><div class="line">    vector&lt;Vec3f&gt; circles;</div><div class="line">    <a class="code" href="../../dd/d1a/group__imgproc__feature.html#ga47849c3be0d0406ad3ca45db65a25d2d">HoughCircles</a>(gray, circles, <a class="code" href="../../dd/d1a/group__imgproc__feature.html#gga073687a5b96ac7a3ab5802eb5510fe65ab1bf00a90864db34b2f72fa76389931d">HOUGH_GRADIENT</a>, 1,</div><div class="line">                 gray.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#abed816466c45234254d25bc59c31245e">rows</a>/16,  <span class="comment">// change this value to detect circles with different distances to each other</span></div><div class="line">                 100, 30, 1, 30 <span class="comment">// change the last two parameters</span></div><div class="line">            <span class="comment">// (min_radius &amp; max_radius) to detect larger circles</span></div><div class="line">    );</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span>( <span class="keywordtype">size_t</span> i = 0; i &lt; circles.size(); i++ )</div><div class="line">    {</div><div class="line">        <a class="code" href="../../d6/dcf/classcv_1_1Vec.html">Vec3i</a> c = circles[i];</div><div class="line">        <a class="code" href="../../db/d4e/classcv_1_1Point__.html">Point</a> center = <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(c[0], c[1]);</div><div class="line">        <span class="comment">// circle center</span></div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gaf10604b069374903dbd0f0488cb43670">circle</a>( src, center, 1, <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0,100,100), 3, <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ggaf076ef45de481ac96e0ab3dc2c29a777a85fdabe5335c9e6656563dfd7c94fb4f">LINE_AA</a>);</div><div class="line">        <span class="comment">// circle outline</span></div><div class="line">        <span class="keywordtype">int</span> radius = c[2];</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gaf10604b069374903dbd0f0488cb43670">circle</a>( src, center, radius, <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255,0,255), 3, <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ggaf076ef45de481ac96e0ab3dc2c29a777a85fdabe5335c9e6656563dfd7c94fb4f">LINE_AA</a>);</div><div class="line">    }</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;detected circles&quot;</span>, src);</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>();</div><div class="line"></div><div class="line">    <span class="keywordflow">return</span> EXIT_SUCCESS;</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'><p> The sample code that we will explain can be downloaded from <a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/java/tutorial_code/ImgTrans/HoughCircle/HoughCircles.java">here</a>. </p><div class="fragment"><div class="line"><span class="keyword">package </span>sample;</div><div class="line"><span class="keyword">import</span> org.opencv.core.*;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Point;</div><div class="line"><span class="keyword">import</span> org.opencv.highgui.HighGui;</div><div class="line"><span class="keyword">import</span> org.opencv.imgcodecs.Imgcodecs;</div><div class="line"><span class="keyword">import</span> org.opencv.imgproc.Imgproc;</div><div class="line"></div><div class="line"><span class="keyword">class </span>HoughCirclesRun {</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="keywordtype">void</span> run(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line"></div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> default_file = <span class="stringliteral">&quot;../../../../data/smarties.png&quot;</span>;</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> filename = ((args.length &gt; 0) ? args[0] : default_file);</div><div class="line"></div><div class="line">        <span class="comment">// Load an image</span></div><div class="line">        Mat src = Imgcodecs.imread(filename, Imgcodecs.IMREAD_COLOR);</div><div class="line"></div><div class="line">        <span class="comment">// Check if image is loaded fine</span></div><div class="line">        <span class="keywordflow">if</span>( src.empty() ) {</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Error opening image!&quot;</span>);</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Program Arguments: [image_name -- default &quot;</span></div><div class="line">                    + default_file +<span class="stringliteral">&quot;] \n&quot;</span>);</div><div class="line">            System.exit(-1);</div><div class="line">        }</div><div class="line"></div><div class="line">        Mat gray = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);</div><div class="line"></div><div class="line">        Imgproc.medianBlur(gray, gray, 5);</div><div class="line"></div><div class="line">        Mat circles = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,</div><div class="line">                (<span class="keywordtype">double</span>)gray.rows()/16, <span class="comment">// change this value to detect circles with different distances to each other</span></div><div class="line">                100.0, 30.0, 1, 30); <span class="comment">// change the last two parameters</span></div><div class="line">                <span class="comment">// (min_radius &amp; max_radius) to detect larger circles</span></div><div class="line"><span class="comment"></span></div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> x = 0; x &lt; circles.cols(); x++) {</div><div class="line">            <span class="keywordtype">double</span>[] c = circles.get(0, x);</div><div class="line">            <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a> center = <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(Math.round(c[0]), Math.round(c[1]));</div><div class="line">            <span class="comment">// circle center</span></div><div class="line">            Imgproc.circle(src, center, 1, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0,100,100), 3, 8, 0 );</div><div class="line">            <span class="comment">// circle outline</span></div><div class="line">            <span class="keywordtype">int</span> radius = (int) Math.round(c[2]);</div><div class="line">            Imgproc.circle(src, center, radius, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255,0,255), 3, 8, 0 );</div><div class="line">        }</div><div class="line"></div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;detected circles&quot;</span>, src);</div><div class="line">        HighGui.waitKey();</div><div class="line"></div><div class="line">        System.exit(0);</div><div class="line">    }</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">class </span><a class="code" href="../../dd/d1a/group__imgproc__feature.html#ga47849c3be0d0406ad3ca45db65a25d2d">HoughCircles</a> {</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keywordtype">void</span> main(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">        <span class="comment">// Load the native library.</span></div><div class="line">        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);</div><div class="line">        <span class="keyword">new</span> HoughCirclesRun().run(args);</div><div class="line">    }</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'><p> The sample code that we will explain can be downloaded from <a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/python/tutorial_code/ImgTrans/HoughCircle/hough_circle.py">here</a>. </p><div class="fragment"><div class="line"><span class="keyword">import</span> sys</div><div class="line"><span class="keyword">import</span> cv2 <span class="keyword">as</span> cv</div><div class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">def </span>main(argv):</div><div class="line">    </div><div class="line">    default_file = <span class="stringliteral">&#39;smarties.png&#39;</span></div><div class="line">    filename = argv[0] <span class="keywordflow">if</span> len(argv) &gt; 0 <span class="keywordflow">else</span> default_file</div><div class="line"></div><div class="line">    <span class="comment"># Loads an image</span></div><div class="line">    src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">cv.imread</a>(<a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">cv.samples.findFile</a>(filename), cv.IMREAD_COLOR)</div><div class="line"></div><div class="line">    <span class="comment"># Check if image is loaded fine</span></div><div class="line">    <span class="keywordflow">if</span> src <span class="keywordflow">is</span> <span class="keywordtype">None</span>:</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Error opening image!&#39;</span>)</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Usage: hough_circle.py [image_name -- default &#39;</span> + default_file + <span class="stringliteral">&#39;] \n&#39;</span>)</div><div class="line">        <span class="keywordflow">return</span> -1</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    gray = <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cv.cvtColor</a>(src, cv.COLOR_BGR2GRAY)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    gray = <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga564869aa33e58769b4469101aac458f9">cv.medianBlur</a>(gray, 5)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    rows = gray.shape[0]</div><div class="line">    circles = <a class="code" href="../../dd/d1a/group__imgproc__feature.html#ga47849c3be0d0406ad3ca45db65a25d2d">cv.HoughCircles</a>(gray, cv.HOUGH_GRADIENT, 1, rows / 8,</div><div class="line">                               param1=100, param2=30,</div><div class="line">                               minRadius=1, maxRadius=30)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    <span class="keywordflow">if</span> circles <span class="keywordflow">is</span> <span class="keywordflow">not</span> <span class="keywordtype">None</span>:</div><div class="line">        circles = np.uint16(np.around(circles))</div><div class="line">        <span class="keywordflow">for</span> i <span class="keywordflow">in</span> circles[0, :]:</div><div class="line">            center = (i[0], i[1])</div><div class="line">            <span class="comment"># circle center</span></div><div class="line">            <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gaf10604b069374903dbd0f0488cb43670">cv.circle</a>(src, center, 1, (0, 100, 100), 3)</div><div class="line">            <span class="comment"># circle outline</span></div><div class="line">            radius = i[2]</div><div class="line">            <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gaf10604b069374903dbd0f0488cb43670">cv.circle</a>(src, center, radius, (255, 0, 255), 3)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&quot;detected circles&quot;</span>, src)</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">cv.waitKey</a>(0)</div><div class="line">    </div><div class="line"></div><div class="line">    <span class="keywordflow">return</span> 0</div><div class="line"></div><div class="line"></div><div class="line"><span class="keywordflow">if</span> __name__ == <span class="stringliteral">&quot;__main__&quot;</span>:</div><div class="line">    main(sys.argv[1:])</div></div><!-- fragment -->  </div> <h2>Explanation </h2>
<p>The image we used can be found <a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/data/smarties.png">here</a></p>
<h4>Load an image:</h4>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span>* filename = argc &gt;=2 ? argv[1] : <span class="stringliteral">&quot;smarties.png&quot;</span>;</div><div class="line"></div><div class="line">    <span class="comment">// Loads an image</span></div><div class="line">    Mat src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>( filename ), <a class="code" href="../../d8/d6a/group__imgcodecs__flags.html#gga61d9b0126a3e57d9277ac48327799c80af660544735200cbe942eea09232eb822">IMREAD_COLOR</a> );</div><div class="line"></div><div class="line">    <span class="comment">// Check if image is loaded fine</span></div><div class="line">    <span class="keywordflow">if</span>(src.empty()){</div><div class="line">        printf(<span class="stringliteral">&quot; Error opening image\n&quot;</span>);</div><div class="line">        printf(<span class="stringliteral">&quot; Program Arguments: [image_name -- default %s] \n&quot;</span>, filename);</div><div class="line">        <span class="keywordflow">return</span> EXIT_FAILURE;</div><div class="line">    }</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">    default_file = <span class="stringliteral">&#39;smarties.png&#39;</span></div><div class="line">    filename = argv[0] <span class="keywordflow">if</span> len(argv) &gt; 0 <span class="keywordflow">else</span> default_file</div><div class="line"></div><div class="line">    <span class="comment"># Loads an image</span></div><div class="line">    src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">cv.imread</a>(<a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">cv.samples.findFile</a>(filename), cv.IMREAD_COLOR)</div><div class="line"></div><div class="line">    <span class="comment"># Check if image is loaded fine</span></div><div class="line">    <span class="keywordflow">if</span> src <span class="keywordflow">is</span> <span class="keywordtype">None</span>:</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Error opening image!&#39;</span>)</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Usage: hough_circle.py [image_name -- default &#39;</span> + default_file + <span class="stringliteral">&#39;] \n&#39;</span>)</div><div class="line">        <span class="keywordflow">return</span> -1</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> default_file = <span class="stringliteral">&quot;../../../../data/smarties.png&quot;</span>;</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> filename = ((args.length &gt; 0) ? args[0] : default_file);</div><div class="line"></div><div class="line">        <span class="comment">// Load an image</span></div><div class="line">        Mat src = Imgcodecs.imread(filename, Imgcodecs.IMREAD_COLOR);</div><div class="line"></div><div class="line">        <span class="comment">// Check if image is loaded fine</span></div><div class="line">        <span class="keywordflow">if</span>( src.empty() ) {</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Error opening image!&quot;</span>);</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Program Arguments: [image_name -- default &quot;</span></div><div class="line">                    + default_file +<span class="stringliteral">&quot;] \n&quot;</span>);</div><div class="line">            System.exit(-1);</div><div class="line">        }</div></div><!-- fragment --> </div> <h4>Convert it to grayscale:</h4>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    Mat gray;</div><div class="line">    <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cvtColor</a>(src, gray, <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#gga4e0972be5de079fed4e3a10e24ef5ef0a353a4b8db9040165db4dacb5bcefb6ea">COLOR_BGR2GRAY</a>);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment"># Convert it to gray</span></div><div class="line">    gray = <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cv.cvtColor</a>(src, cv.COLOR_BGR2GRAY)</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">        Mat gray = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);</div></div><!-- fragment --> </div> <h4>Apply a Median blur to reduce noise and avoid false circle detection:</h4>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga564869aa33e58769b4469101aac458f9">medianBlur</a>(gray, gray, 5);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment"># Reduce the noise to avoid false circle detection</span></div><div class="line">    gray = <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga564869aa33e58769b4469101aac458f9">cv.medianBlur</a>(gray, 5)</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">        Imgproc.medianBlur(gray, gray, 5);</div></div><!-- fragment --> </div> <h4>Proceed to apply Hough Circle Transform:</h4>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    vector&lt;Vec3f&gt; circles;</div><div class="line">    <a class="code" href="../../dd/d1a/group__imgproc__feature.html#ga47849c3be0d0406ad3ca45db65a25d2d">HoughCircles</a>(gray, circles, <a class="code" href="../../dd/d1a/group__imgproc__feature.html#gga073687a5b96ac7a3ab5802eb5510fe65ab1bf00a90864db34b2f72fa76389931d">HOUGH_GRADIENT</a>, 1,</div><div class="line">                 gray.rows/16,  <span class="comment">// change this value to detect circles with different distances to each other</span></div><div class="line">                 100, 30, 1, 30 <span class="comment">// change the last two parameters</span></div><div class="line">            <span class="comment">// (min_radius &amp; max_radius) to detect larger circles</span></div><div class="line">    );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">    rows = gray.shape[0]</div><div class="line">    circles = <a class="code" href="../../dd/d1a/group__imgproc__feature.html#ga47849c3be0d0406ad3ca45db65a25d2d">cv.HoughCircles</a>(gray, cv.HOUGH_GRADIENT, 1, rows / 8,</div><div class="line">                               param1=100, param2=30,</div><div class="line">                               minRadius=1, maxRadius=30)</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">        Mat circles = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,</div><div class="line">                (<span class="keywordtype">double</span>)gray.rows()/16, <span class="comment">// change this value to detect circles with different distances to each other</span></div><div class="line">                100.0, 30.0, 1, 30); <span class="comment">// change the last two parameters</span></div><div class="line">                <span class="comment">// (min_radius &amp; max_radius) to detect larger circles</span></div></div><!-- fragment --> </div> <ul>
<li>with the arguments:<ul>
<li><em>gray</em>: Input image (grayscale).</li>
<li><em>circles</em>: A vector that stores sets of 3 values: \(x_{c}, y_{c}, r\) for each detected circle.</li>
<li><em>HOUGH_GRADIENT</em>: Define the detection method. Currently this is the only one available in OpenCV.</li>
<li><em>dp = 1</em>: The inverse ratio of resolution.</li>
<li><em>min_dist = gray.rows/16</em>: Minimum distance between detected centers.</li>
<li><em>param_1 = 200</em>: Upper threshold for the internal Canny edge detector.</li>
<li><em>param_2</em> = 100*: Threshold for center detection.</li>
<li><em>min_radius = 0</em>: Minimum radius to be detected. If unknown, put zero as default.</li>
<li><em>max_radius = 0</em>: Maximum radius to be detected. If unknown, put zero as default.</li>
</ul>
</li>
</ul>
<h4>Draw the detected circles:</h4>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="keywordflow">for</span>( <span class="keywordtype">size_t</span> i = 0; i &lt; circles.size(); i++ )</div><div class="line">    {</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga55864bca2bbede9731df5baa0d1be763">Vec3i</a> c = circles[i];</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a> center = <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(c[0], c[1]);</div><div class="line">        <span class="comment">// circle center</span></div><div class="line">        <a class="code" href="../../d9/db7/group__datasets__gr.html#gga610754124ced68d1f05760b5948fbb76a6f0d8b2d9e3e947b2a5c1eff9e81ee95">circle</a>( src, center, 1, <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0,100,100), 3, <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ggaf076ef45de481ac96e0ab3dc2c29a777a85fdabe5335c9e6656563dfd7c94fb4f">LINE_AA</a>);</div><div class="line">        <span class="comment">// circle outline</span></div><div class="line">        <span class="keywordtype">int</span> radius = c[2];</div><div class="line">        <a class="code" href="../../d9/db7/group__datasets__gr.html#gga610754124ced68d1f05760b5948fbb76a6f0d8b2d9e3e947b2a5c1eff9e81ee95">circle</a>( src, center, radius, <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255,0,255), 3, <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ggaf076ef45de481ac96e0ab3dc2c29a777a85fdabe5335c9e6656563dfd7c94fb4f">LINE_AA</a>);</div><div class="line">    }</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">    <span class="keywordflow">if</span> circles <span class="keywordflow">is</span> <span class="keywordflow">not</span> <span class="keywordtype">None</span>:</div><div class="line">        circles = np.uint16(np.around(circles))</div><div class="line">        <span class="keywordflow">for</span> i <span class="keywordflow">in</span> circles[0, :]:</div><div class="line">            center = (i[0], i[1])</div><div class="line">            <span class="comment"># circle center</span></div><div class="line">            <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gaf10604b069374903dbd0f0488cb43670">cv.circle</a>(src, center, 1, (0, 100, 100), 3)</div><div class="line">            <span class="comment"># circle outline</span></div><div class="line">            radius = i[2]</div><div class="line">            <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gaf10604b069374903dbd0f0488cb43670">cv.circle</a>(src, center, radius, (255, 0, 255), 3)</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> x = 0; x &lt; circles.cols(); x++) {</div><div class="line">            <span class="keywordtype">double</span>[] c = circles.get(0, x);</div><div class="line">            <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a> center = <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(Math.round(c[0]), Math.round(c[1]));</div><div class="line">            <span class="comment">// circle center</span></div><div class="line">            Imgproc.circle(src, center, 1, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0,100,100), 3, 8, 0 );</div><div class="line">            <span class="comment">// circle outline</span></div><div class="line">            <span class="keywordtype">int</span> radius = (int) Math.round(c[2]);</div><div class="line">            Imgproc.circle(src, center, radius, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255,0,255), 3, 8, 0 );</div><div class="line">        }</div></div><!-- fragment --> </div> <p>You can see that we will draw the circle(s) on red and the center(s) with a small green dot</p>
<h4>Display the detected circle(s) and wait for the user to exit the program:</h4>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;detected circles&quot;</span>, src);</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>();</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">    <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&quot;detected circles&quot;</span>, src)</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">cv.waitKey</a>(0)</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;detected circles&quot;</span>, src);</div><div class="line">        HighGui.waitKey();</div></div><!-- fragment --> </div> <h2>Result </h2>
<p>The result of running the code above with a test image is shown below:</p>
<div class="image">
<img src="../../Hough_Circle_Tutorial_Result.png" alt="Hough_Circle_Tutorial_Result.png"/>
</div>
 </div></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Apr 2 2021 11:36:35 for OpenCV by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
